/*
 * index.c
 *
 *  Created on: Jul 18, 2012
 *      Author: baris
 */

#include <assert.h>

#include "index.h"
#include "../model/datatypes.h"

// add s to the told subsumer list of c
// note that multiple occurrence of s is allowed!
void add_told_subsumer(Concept* c, Concept* s) {
	Concept** tmp;

	tmp = realloc(c->told_subsumers, (c->told_subsumer_count + 1) * sizeof(Concept*));
	assert(tmp != NULL);
	c->told_subsumers = tmp;
	c->told_subsumers[c->told_subsumer_count] = s;
	c->told_subsumer_count++;
}

void add_to_filler_of_list(Concept* f, Concept* ex) {
	Concept** tmp;

	// TODO: Is this correct? Check! -> sizeof(Exists*)?? why not size of sizeof(Concept*) ??
	// tmp = realloc(f->filler_of_exists_restrictions, (f->filler_of_count + 1) * sizeof(Exists*));
	tmp = realloc(f->filler_of_exists_restrictions, (f->filler_of_count + 1) * sizeof(Concept*));
	assert(tmp != NULL);
	f->filler_of_exists_restrictions = tmp;
	f->filler_of_exists_restrictions[f->filler_of_count] = ex;
	f->filler_of_count++;
}

void add_to_conjunct_of_list(Concept* concept, Concept* conjunction) {
	Concept** tmp;

	tmp = realloc(concept->conjunct_of, (concept->conjunct_of_count + 1) * sizeof(Concept*));
	assert(tmp != NULL);
	concept->conjunct_of = tmp;
	concept->conjunct_of[concept->conjunct_of_count] = conjunction;
	concept->conjunct_of_count++;
}

void index_concept(Concept* c) {
	int i;

	switch (c->type) {
	case ATOMIC_CONCEPT:
		break;
	case CONJUNCTION:
		for (i = 0; i < c->description.conj->size; i++) {
			index_concept(c->description.conj->conjuncts[i]);
			add_to_conjunct_of_list(c->description.conj->conjuncts[i], c);
		}
		break;
	case EXISTENTIAL_RESTRICTION:
		add_to_filler_of_list(c->description.exists->filler, c);
		index_concept(c->description.exists->filler);
		break;
	default:
		fprintf(stderr, "unknown concept type, aborting\n");
		exit(EXIT_FAILURE);
	}
}

void index_tbox(TBox* tbox) {
	int i;

	for (i = 0; i < tbox->subclass_axiom_count; i++) {
		add_told_subsumer(tbox->subclass_axioms[i]->lhs, tbox->subclass_axioms[i]->rhs);
		index_concept(tbox->subclass_axioms[i]->lhs);
	}

	for (i = 0; i < tbox->eqclass_axiom_count; i++) {
		add_told_subsumer(tbox->eqclass_axioms[i]->lhs, tbox->eqclass_axioms[i]->rhs);
		index_concept(tbox->eqclass_axioms[i]->lhs);
		add_told_subsumer(tbox->eqclass_axioms[i]->rhs, tbox->eqclass_axioms[i]->lhs);
		index_concept(tbox->eqclass_axioms[i]->rhs);
	}
}
